package cl.fbd.widget.treetable

import cl.fbd.widget.model._

import scala.xml.NodeSeq

/**
 *
 */
 
class TreeTableGenerator [A] (
	treeModel : TreeModel [A],
	idTable : String,  // it seems that jqTreeTable support only "tablemain" as idTable 
	idTbody : String,  // it seems that jqTreeTable support only "treetable" as idTbody
	extractor : ColumnExtractor[A], 
  showRoot : Boolean
	)  
{
  val rows : List [Pair [A, NodeInfo]] = if (showRoot) treeModel.preorder else treeModel.preorder.drop (1)
	  
  /**
   * generate the content of the jqTreeTable's javascript "map" var  
   */
  
  def generateMap () : String = {
    def _generateMap (_rows : List [Pair [A, NodeInfo]]) : String = {
      _rows match {
        case List (last) => last._2.parentId.toString
        case head :: tail => head._2.parentId.toString + ", " + _generateMap (tail)
      }
    }
    
    _generateMap (rows)
  }
  
  private def _generateCollapse (_rows : List [Pair [A, NodeInfo]]) : String = {
    _rows match {
      case Nil => ""
      case List (last) => last._2.id.toString
      case head :: tail => head._2.id.toString + ", " + _generateCollapse (tail)
    }
  }
  
  /**
   * generate the list of collapsed node  
   */
   
  def generateCollapse () : String = {
    println ("generateCollapse")
    
    val rowsToCollapse = rows.filter (row => row._2.isCollapsed) 
    
    println (rowsToCollapse)
    
    rowsToCollapse match {
      case Nil => "false"
      case _ => "[" + _generateCollapse (rowsToCollapse) + "]" 
    }
  }
  
  /**
   * generate the list of collapsed node (the ones at level {level}) 
   */
   
  def generateCollapse (level : Int) : String = {
    println ("generateCollapse  " + level)
    
    val rowsToCollapse = rows.filter (row => row._2.level == level) // jqQuery take care of sub-rows
    
    println (rowsToCollapse)
    
    "[" + _generateCollapse (rowsToCollapse) + "]" 
  }
  
  
  /**
   * generate the HTML table 
   */
  
  def generateXhtml () : NodeSeq = {
    <table id={idTable}>
		<thead>
			<tr>
      {extractor.headers.flatMap (header => {
				<td>
          {(header)}
        </td>
        })
      }
			</tr>
		</thead>
		<tbody id={idTbody}>
    {
      rows.flatMap (row => {
        <tr>
          {extractor.cells (row._1).flatMap (cell => {
		   		 <td>
             {cell}
           </td>
            })
          }
        </tr>
      })
    }
		</tbody>
	</table>
    
  }
}
